package org.hepeng.workx.util.serializer;


import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.ArrayUtils;

import java.util.Objects;

/**
 * @author he peng
 */
public abstract class ExceptionTranslationObjectSerializer<T> implements ObjectSerializer<T> {

    protected Class<T> serializationClass;

    @Override
    public byte[] serialize(T object) throws SerializationException {
        if (Objects.isNull(object)) {
            return null;
        }

        try {
            return convert(object);
        } catch (Throwable t) {
            throw new SerializationException("Serialize Error :" + t.getMessage() , t);
        }
    }


    @Override
    public T deserialize(byte[] bytes) throws SerializationException {
        if (ArrayUtils.isEmpty(bytes)) {
            return null;
        }

        try {
            return convert(bytes);
        } catch (Throwable t) {
            throw new SerializationException("Deserialize Error :" + t.getMessage() , t);
        }
    }

    @Override
    public String serializeBase64String(T object) throws SerializationException {
        return Base64.encodeBase64String(serialize(object));
    }

    @Override
    public T deserializeBase64String(String base64Str) throws SerializationException {
        return deserialize(Base64.decodeBase64(base64Str));
    }

    protected abstract byte[] convert(T object) throws Exception;

    protected abstract T convert(byte[] bytes) throws Exception;
}
